package com.knife.blog.logic.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import com.knife.blog.domain.BlogInfo;
import com.knife.blog.domain.UserConfig;
import com.knife.blog.logic.UserConfigService;
import com.knife.blog.util.XmlparseUtil;
import com.knife.web.Globals;

public class UserConfigServiceImpl extends DAOSupportService implements UserConfigService {
	private Document doc;
	
	private static UserConfigServiceImpl configService = new UserConfigServiceImpl(); 
	
	private UserConfigServiceImpl(){
		
	}
	
	public UserConfigService getInstance(){
		return configService;
	}
	
	private void init(){
		
	}

	public UserConfig getConfig(File file) {
		// TODO 自动生成方法存根
		//File file = new File(Globals.DEFAULT_TEMPLATE_PATH+"/blog/userConfig.xml");
		UserConfig config = new UserConfig();
		FileInputStream in=null;
		try {
			in = new FileInputStream(file);
			doc = new XmlparseUtil().initDoc(in);
		} catch (FileNotFoundException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		doc2Config(doc,config);
		return config;
	}

	public UserConfig getConfig(BlogInfo blog) {
		// TODO 自动生成方法存根
		File file = new File(Globals.APP_BASE_DIR+"/"+blog.getDomain()+"/config/userConfig.xml");
		return getConfig(file);
	}

	public boolean saveConfig(Document doc) {
		// TODO 自动生成方法存根
		
		return false;
	}

	public UserConfig getConfig(String domain) {
		// TODO 自动生成方法存根
		File file = new File(Globals.APP_BASE_DIR+"/"+domain+"/config/userConfig.xml");
		return getConfig(file);
	}
	
	public void doc2Config(Document doc,UserConfig config){
		String style;
		String structure;
		Element e;
		List modules = new ArrayList();
		e = (Element)doc.selectNodes("/config/style").get(0);
		style = e.attributeValue("name");
		e = (Element)doc.selectNodes("/config/structure").get(0);
		structure = e.attributeValue("name");
		List nodes = doc.selectNodes("/config/modules/module");
		for(int i=0;i<nodes.size();i++){
			e = (Element)nodes.get(i);
			String status = e.attributeValue("status");
			if(status.equals("view")){
				Map values = new HashMap();
				String name = e.attributeValue("name");
				int index = new Integer(e.attributeValue("index"));
				values.put("name", name);
				values.put("index", index);
				modules.add(values);
			}
		}
		config.setStyle(style);
		config.setStructure(structure);
		config.setModule(modules);
		config.setModules(modules.size());
	}
	
	public void config2Doc(Document doc,UserConfig config){
		
	}

}
